from rest_framework import viewsets, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from submission.models.submission_model import SubmissionModel
from submission.serializers.serializers import SubmissionSerializer, SubmissionCreateSerializer
from submission.service.submission_service import SubmissionService
from weiwenhai_Oj.utils.global_functions import returnResponse, PageSizePagination
from django.db.models import Q


class SubmissionViewSet(viewsets.ModelViewSet):
    """提交记录视图集"""
    queryset = SubmissionModel.objects.filter(is_delete=False).order_by('-create_time')
    serializer_class = SubmissionSerializer
    pagination_class = PageSizePagination
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.action == 'create':
            return SubmissionCreateSerializer
        return SubmissionSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        problem_id = self.request.query_params.get('problem')
        if problem_id:
            queryset = queryset.filter(problem_id=problem_id)
        return queryset.filter(user=self.request.user)

    @action(detail=False, methods=['post'], url_path='submit')
    def submit_code(self, request):
        """提交代码"""
        try:
            # 验证请求数据
            serializer = SubmissionCreateSerializer(data=request.data)
            if not serializer.is_valid():
                return returnResponse({
                    'code': 400,
                    'msg': '参数错误',
                    'data': serializer.errors
                })

            # 创建提交记录
            submission = SubmissionService.create_submission(
                user_id=request.user.id,
                problem_id=serializer.validated_data['problem'],
                language=serializer.validated_data['language'],
                code=serializer.validated_data['code']
            )

            return returnResponse({
                'code': 200,
                'msg': '提交成功',
                'data': SubmissionSerializer(submission).data
            })
        except ValueError as e:
            return returnResponse({
                'code': 400,
                'msg': str(e),
                'data': None
            })
        except Exception as e:
            return returnResponse({
                'code': 500,
                'msg': str(e),
                'data': None
            })

    def create(self, request, *args, **kwargs):
        """创建提交记录（兼容旧接口）"""
        return self.submit_code(request)

    def list(self, request, *args, **kwargs):
        """获取提交记录列表"""
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)

        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return returnResponse({
                'code': 200,
                'msg': '获取成功',
                'count': self.get_paginated_response(serializer.data).data.get('count'),
                'data': self.get_paginated_response(serializer.data).data.get('results')
            })

        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'code': 200,
            'message': 'success',
            'data': serializer.data
        })


    def retrieve(self, request, *args, **kwargs):
        """获取提交记录详情"""
        try:
            instance = self.get_object()
            serializer = self.get_serializer(instance)
            return returnResponse({
                'code': 200,
                'msg': '获取成功',
                'data': serializer.data
            })
        except Exception as e:
            return returnResponse({
                'code': 500,
                'msg': str(e),
                'data': None
            })